﻿using AutoMapper;
using HomeCareLibrary.AppService;
using HomeCareLibrary.Constants;
using HomeCareLibrary.Core.DataContracts;
using HomeCareLibrary.Core.Dtos;
using HomeCareLibrary.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
//using System.Windows.Forms;
//using Omu.Drawing;
using System.Drawing;
using Omu.Drawing;

namespace HomeCareLibrary.Controllers
{
    // commented by Laxman on 30 Jan 2014 for allowing Android App developers to use pages with out authentication
    // [Authorize] 
    public class AdminController : BaseController
    {
        //
        // GET: /Admin/
        private homewizard_test2databaseEntities db = new homewizard_test2databaseEntities();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult MonthlyReminder()
        {

            //Session[SessionConstants.MODE] = ApplicationModeConstants.ANDROID_APP; //Only for Testing

            ViewBag.sessionIds = "Session Id: " + Session.SessionID.ToString() + ", " + SessionConstants.USER_ID + "=" + Session[SessionConstants.USER_ID] + ", " + SessionConstants.USER_NAME + "=" + Session[SessionConstants.USER_NAME] + ", " + SessionConstants.PASSWORD + "=" + Session[SessionConstants.PASSWORD] + ", " + SessionConstants.MODE + "=" + Session[SessionConstants.MODE] + ", " + SessionConstants.ACTIVITY_TYPE + "=" + Session[SessionConstants.ACTIVITY_TYPE] + ", " + SessionConstants.PROMO_CODE + "=" + Session[SessionConstants.PROMO_CODE] + ", " + SessionConstants.SPONSOR_DETAILS + "=" + Session[SessionConstants.SPONSOR_DETAILS];
            string str = null;
            foreach (string key in Session.Keys)
            {
                try
                {
                    if (Session[key] != null)
                    {

                        str += string.Format("{0}: {1}<br />", key, Session[key].ToString());
                    }
                }
                catch
                { }
            }
            ViewBag.getSession = str;

            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;


            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;


            UserDetailIDModel model = new UserDetailIDModel();

            if (Session[SessionConstants.USER_ID] != null)
            {

                #region [Get UserDetail from Database table 'User_Details' according to SessionConstants.USER_ID and "Home Number"]
                Int32 userId = Convert.ToInt32(Session[SessionConstants.USER_ID].ToString());
                Int32 homeNumber = 1;
                DataRepository entities = new DataRepository();
                if (Session[SessionConstants.HOME_NUMBER] == null)
                {
                    var getHomeNumber = entities.getMultipleHomesByUserID(userId);
                    homeNumber = Convert.ToInt32(getHomeNumber);
                    Session[SessionConstants.HOME_NUMBER] = homeNumber;
                }

                else if (Convert.ToInt32(Session[SessionConstants.HOME_NUMBER]) == 0)
                {

                    var getHomeNumber = entities.getMultipleHomesByUserID(userId);
                    homeNumber = Convert.ToInt32(getHomeNumber);
                    Session[SessionConstants.HOME_NUMBER] = homeNumber;
                }
                else
                {
                    homeNumber = Convert.ToInt32(Session[SessionConstants.HOME_NUMBER].ToString());
                }

                PersonalisationAppService objPersonalisationAppService = new PersonalisationAppService();
                GetKLByUserIdHomeNumberRequest objGetKLByUserIdHomeNumberRequest = new GetKLByUserIdHomeNumberRequest();
                objGetKLByUserIdHomeNumberRequest.UserId = userId;
                objGetKLByUserIdHomeNumberRequest.HomeNumber = homeNumber;

                var getPriority = objPersonalisationAppService.GetMonthlyAlertSettingsByUserIdHomeNumber(objGetKLByUserIdHomeNumberRequest).SingleOrDefault();
                Mapper.CreateMap<CTGetMonthlyAlertSettingsByUserIdHomeNumberDto, UserDetailIDModel>();
                Mapper.Map<CTGetMonthlyAlertSettingsByUserIdHomeNumberDto, UserDetailIDModel>(getPriority, model);

                #endregion

                #region[App Bind]
                ViewBag.getWeekoftheMonth = new SelectList(GetWeekOfTheMonth(), "Value", "Text", model.app_mo_alert_week);
                ViewBag.getDayoftheWeek = new SelectList(GetDayOfTheWeek(), "Value", "Text", model.app_mo_alert_day);
                ViewBag.getTimeoftheDay = new SelectList(GetTimeOfTheDay(), "Value", "Text", model.app_mo_alert_hour);
                #endregion
                return View("monthlyreminder", model);
            }
            else
            {
                return RedirectToAction("Login", "Home");
            }


        }

        public ActionResult PromoCode()
        {
            //Session[SessionConstants.MODE] = ApplicationModeConstants.ANDROID_APP; //Only for Testing

            ViewBag.sessionIds = "Session Id: " + Session.SessionID.ToString() + ", " + SessionConstants.USER_ID + "=" + Session[SessionConstants.USER_ID] + ", " + SessionConstants.USER_NAME + "=" + Session[SessionConstants.USER_NAME] + ", " + SessionConstants.PASSWORD + "=" + Session[SessionConstants.PASSWORD] + ", " + SessionConstants.MODE + "=" + Session[SessionConstants.MODE] + ", " + SessionConstants.ACTIVITY_TYPE + "=" + Session[SessionConstants.ACTIVITY_TYPE] + ", " + SessionConstants.PROMO_CODE + "=" + Session[SessionConstants.PROMO_CODE] + ", " + SessionConstants.SPONSOR_DETAILS + "=" + Session[SessionConstants.SPONSOR_DETAILS];

            string str = null;
            foreach (string key in Session.Keys)
            {
                try
                {
                    if (Session[key] != null)
                    {

                        str += string.Format("{0}: {1}<br />", key, Session[key].ToString());
                    }
                }
                catch
                { }
            }
            ViewBag.getSession = str;


            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;


            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;

            var model = new PromoCodeModel();

            if (Session[SessionConstants.USER_ID] != null)
            {
                Int32 userId = Convert.ToInt32(Session[SessionConstants.USER_ID].ToString());
                DataRepository entities = new DataRepository();
                model = entities.getAdminPromoCode_UserID(userId);

                return View("promocode", model);
            }
            else
            {
                return RedirectToAction("Login", "Home");
            }


        }

        [HttpPost]
        public ActionResult UpdateWebMonthlyReminder(UserDetailIDModel model)
        {
            DataRepository entities = new DataRepository();
            entities.UpdateWebMonthlyReminder(model);

            TempData["messageweb"] = "Email updated";
            return RedirectToAction("MonthlyReminder");

        }
        [HttpPost]
        public ActionResult UpdateAndroidMonthlyReminder(UserDetailIDModel model)
        {
            DataRepository entities = new DataRepository();
            entities.UpdateAndroidMonthlyReminder(model);

            TempData["messageandroid"] = "updated";
            return RedirectToAction("MonthlyReminder");
        }

        #region[Promo Code]



        [HttpPost]
        public ActionResult UpdatePromocode(PromoCodeModel model)
        {
            string str = null;
            foreach (string key in Session.Keys)
            {
                try
                {
                    if (Session[key] != null)
                    {

                        str += string.Format("{0}: {1}<br />", key, Session[key].ToString());
                    }
                }
                catch
                { }
            }
            ViewBag.getSession = str;
            ViewBag.sessionIds = "Session Id: " + Session.SessionID.ToString() + ", " + "Session Id: " + Session.SessionID.ToString() + ", " + SessionConstants.USER_ID + "=" + Session[SessionConstants.USER_ID] + ", " + SessionConstants.USER_NAME + "=" + Session[SessionConstants.USER_NAME] + ", " + SessionConstants.PASSWORD + "=" + Session[SessionConstants.PASSWORD] + ", " + SessionConstants.MODE + "=" + Session[SessionConstants.MODE] + ", " + SessionConstants.ACTIVITY_TYPE + "=" + Session[SessionConstants.ACTIVITY_TYPE] + ", " + SessionConstants.PROMO_CODE + "=" + Session[SessionConstants.PROMO_CODE] + ", " + SessionConstants.SPONSOR_DETAILS + "=" + Session[SessionConstants.SPONSOR_DETAILS];

            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;


            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;


            //Session[SessionConstants.MODE] = ApplicationModeConstants.IPHONE_APP; //Only for Testing

            //String result = "0";

            if (model.user_id > 0)
            {
                Int32 userId = model.user_id;

                if (String.IsNullOrEmpty(model.sponsor) && !String.IsNullOrEmpty(model.ChangePromocode))
                {
                    TempData["getMessage"] = "To delete Promo Code, use the 'Delete' link.";
                }

                else if (!String.IsNullOrEmpty(model.ChangePromocode))
                {
                    DataRepository entities = new DataRepository();
                    var getResult = entities.updatePromocode(userId, model.sponsor, model.DeletePromocode, model.ChangePromocode).SingleOrDefault();
                    DeleteSponsorSessionData();
                    Session[SessionConstants.PROMO_CODE] = model.sponsor;
                    if (getResult.promoCodeChange == "activePromocodeConfirmed")
                    {
                        TempData["getMessage"] = "Promo Code updated.";
                        Session[SessionConstants.IS_PROMO_CODE_ACTIVE] = "foundActive";
                        
                        var sponsorService = new SponsorAppService();
                        var sponsorSessionData = sponsorService.GetSponsorInput345xData(model.sponsor);
                        Session[SessionConstants.SPONSOR_DETAILS] = sponsorSessionData;
                    }
                    else if (getResult.promoCodeChange == "inactivePromocodeConfirmed")
                    {
                        TempData["getMessage"] = "The Promo Code that you entered is not active at this time.";
                        Session[SessionConstants.IS_PROMO_CODE_ACTIVE] = "foundInactive";
                    }

                    else if ((getResult.promoCodeChange == "failed") || (getResult.promoCodeChange == "empty") || (getResult.promoCodeChange == "errorInUpdating"))
                    {
                        TempData["getMessage"] = "Sorry, the Promo Code that you entered is not valid.";
                        Session[SessionConstants.IS_PROMO_CODE_ACTIVE] = "notFound";
                    }
                }
                else if (!String.IsNullOrEmpty(model.DeletePromocode))
                {

                    DataRepository entities = new DataRepository();
                    var getResult = entities.updatePromocode(userId, model.sponsor, model.DeletePromocode, model.ChangePromocode).SingleOrDefault();
                    DeleteSponsorSessionData();
                    Session[SessionConstants.PROMO_CODE] = null;
                    Session[SessionConstants.IS_PROMO_CODE_ACTIVE] = "notFound";
                    if (getResult.promocodeDeleted == "deleted")
                    {
                        TempData["getMessage"] = "Promo Code deleted.";
                    }
                    else if (getResult.promocodeDeleted == "empty")
                    {
                        TempData["getMessage"] = "Promo Code deleted.";
                    }
                    model.sponsor = null;

                }

                return RedirectToAction("PromoCode");

            }
            else
            {
                return RedirectToAction("Login", "Home");

            }
        }



        [HttpPost]
        public JsonResult DeletePromoCode(String userid, String Promocode, String DeletePromocode, String ChangePromocode)
        {
            String result = "0";

            if (!String.IsNullOrEmpty(userid))
            {
                Int32 userId = Convert.ToInt32(userid);

                DataRepository entities = new DataRepository();
                var getResult = entities.updatePromocode(userId, Promocode, DeletePromocode, ChangePromocode);

                DeleteSponsorSessionData();
                Session[SessionConstants.PROMO_CODE] = null;
                return Json(new { JsonResult = getResult }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(result, JsonRequestBehavior.AllowGet);
            }
        }


        public void DeleteSponsorSessionData()
        {

            //Session[SessionConstants.SPON_PIC]=null;
            //Session[SessionConstants.SPON_LOGO] = null;
            //Session[SessionConstants.SPON_LOGO_TAG] = null;
            //Session[SessionConstants.SPON_YOURNAME] = null;
            //Session[SessionConstants.SPON_PHONEBAN] = null;
            //Session[SessionConstants.SPON_EMAIL] = null;
            //Session[SessionConstants.SPON_WEB_ADD] = null;

        }

        #endregion


        #region[Common Functions]
        public SelectListItem[] GetWeekOfTheMonth()
        {
            return new[]
        {
           new SelectListItem { Value = "1", Text = "First week of the month" },
           new SelectListItem { Value = "2", Text = "Second week of the month" },
           new SelectListItem { Value = "3", Text = "Third week of the month" },
           new SelectListItem { Value = "4", Text = "Fourth week of the month" },
          
        };

        }
        public SelectListItem[] GetDayOfTheWeek()
        {
            return new[]
        {
           new SelectListItem { Value = "1", Text = "Sunday" },
           new SelectListItem { Value = "2", Text = "Monday" },
           new SelectListItem { Value = "3", Text = "Tuesday" },
           new SelectListItem { Value = "4", Text = "Wednesday" },
           new SelectListItem { Value = "5", Text = "Thursday" },
           new SelectListItem { Value = "6", Text = "Friday" },
           new SelectListItem { Value = "7", Text = "Saturday" },
          
        };

        }

        public SelectListItem[] GetTimeOfTheDay()
        {
            return new[]
        {
          
           new SelectListItem { Value = "0", Text = "midnight" },
           new SelectListItem { Value = "1", Text = "1 am" },
           new SelectListItem { Value = "2", Text = "2 am" },
           new SelectListItem { Value = "3", Text = "3 am" },
           new SelectListItem { Value = "4", Text = "4 am" },
           new SelectListItem { Value = "5", Text = "5 am" },
           new SelectListItem { Value = "6", Text = "6 am" },
           new SelectListItem { Value = "7", Text = "7 am" },
           new SelectListItem { Value = "8", Text = "8 am" },
           new SelectListItem { Value = "9", Text = "9 am" },
           new SelectListItem { Value = "10", Text = "10 am" },
           new SelectListItem { Value = "11", Text = "11 am" },
           new SelectListItem { Value = "12", Text = "12 pm" },
           new SelectListItem { Value = "13", Text = "1 pm" },
           new SelectListItem { Value = "14", Text = "2 pm" },
           new SelectListItem { Value = "15", Text = "3 pm" },
           new SelectListItem { Value = "16", Text = "4 pm" },
           new SelectListItem { Value = "17", Text = "5 pm" },
           new SelectListItem { Value = "18", Text = "6 pm" },
           new SelectListItem { Value = "19", Text = "7 pm" },
           new SelectListItem { Value = "20", Text = "8 pm" },
           new SelectListItem { Value = "21", Text = "9 pm" },
           new SelectListItem { Value = "22", Text = "10 pm" },
           new SelectListItem { Value = "23", Text = "11 pm" }
           
        };

        }


        public ActionResult WelcomeImage()
        {
            //Session[SessionConstants.MODE] = ApplicationModeConstants.ANDROID_APP; //Only for Testing


            if (Session[SessionConstants.USER_ID] != null)
            {


                UserAppService objUserAppService = new UserAppService();
                Int32 userId = Convert.ToInt32(Session[SessionConstants.USER_ID].ToString());
                ViewBag.getWelcomeImage = objUserAppService.GetWelcomeImage(userId);
                ViewBag.sessionIds = "Session Id: " + Session.SessionID.ToString() + ", " + "Session Id: " + Session.SessionID.ToString() + ", " + SessionConstants.USER_ID + "=" + Session[SessionConstants.USER_ID] + ", " + SessionConstants.USER_NAME + "=" + Session[SessionConstants.USER_NAME] + ", " + SessionConstants.PASSWORD + "=" + Session[SessionConstants.PASSWORD] + ", " + SessionConstants.MODE + "=" + Session[SessionConstants.MODE] + ", " + SessionConstants.ACTIVITY_TYPE + "=" + Session[SessionConstants.ACTIVITY_TYPE] + ", " + SessionConstants.PROMO_CODE + "=" + Session[SessionConstants.PROMO_CODE] + ", " + SessionConstants.SPONSOR_DETAILS + "=" + Session[SessionConstants.SPONSOR_DETAILS];

                string str = null;
                foreach (string key in Session.Keys)
                {
                    try
                    {
                        if (Session[key] != null)
                        {

                            str += string.Format("{0}: {1}<br />", key, Session[key].ToString());
                        }
                    }
                    catch
                    { }
                }
                ViewBag.getSession = str;


                Request.InputStream.Position = 0;
                StreamReader postedVariableStream = new StreamReader(Request.InputStream);
                string postedVariableJsonString = postedVariableStream.ReadToEnd();
                ViewBag.JsonString = postedVariableJsonString;

                string getContentType = Request.ContentType;
                ViewBag.ContentType = getContentType;

                string getRequestUrl = Request.Url.ToString();
                ViewBag.Url = getRequestUrl;

                //string promoCode = Session[SessionConstants.PROMO_CODE].ToString();                       

                //string sponsor = db.User_ID.Where(w=>w.user_id1 == userId).Select(s=>s.sponsor).FirstOrDefault();
                //var sponsorDetail = db.SponsorInputs345x.Where(w => w.sponsor == sponsor).Select(s => s).FirstOrDefault();
                SponsorInputs345xModel model = new SponsorInputs345xModel();
                var getSponsorDetail = (HomeCareLibrary.Core.Dtos.SponsorInputs345xDto)Session[HomeCareLibrary.Constants.SessionConstants.SPONSOR_DETAILS];

                if (getSponsorDetail != null)
                {
                    model.ilogo_pic = getSponsorDetail.ilogo_pic;
                    model.web_notepad_line1 = getSponsorDetail.web_notepad_line1;
                    model.web_notepad_line2 = getSponsorDetail.web_notepad_line2;
                    model.web_notepad_line3 = getSponsorDetail.web_notepad_line3;
                    model.web_notepad_line4 = getSponsorDetail.web_notepad_line4;
                    model.web_notepad_line5 = getSponsorDetail.web_notepad_line5;
                    model.web_notepad_line6 = getSponsorDetail.web_notepad_line6;
                }
                if (Session[SessionConstants.USER_ID] != null)
                {
                    return View(model);
                }
                else
                {
                    return RedirectToAction("Login", "Home");
                }

            }
            else
            {
                return RedirectToAction("Login", "Home");
            }
        }

        public ActionResult HelpFAQs()
        {
            ViewBag.sessionIds = "Session Id: " + Session.SessionID.ToString() + ", " + SessionConstants.USER_ID + "=" + Session[SessionConstants.USER_ID] + ", " + SessionConstants.USER_NAME + "=" + Session[SessionConstants.USER_NAME] + ", " + SessionConstants.PASSWORD + "=" + Session[SessionConstants.PASSWORD] + ", " + SessionConstants.MODE + "=" + Session[SessionConstants.MODE] + ", " + SessionConstants.ACTIVITY_TYPE + "=" + Session[SessionConstants.ACTIVITY_TYPE] + ", " + SessionConstants.PROMO_CODE + "=" + Session[SessionConstants.PROMO_CODE] + ", " + SessionConstants.SPONSOR_DETAILS + "=" + Session[SessionConstants.SPONSOR_DETAILS];

            string str = null;
            foreach (string key in Session.Keys)
            {
                try
                {
                    if (Session[key] != null)
                    {

                        str += string.Format("{0}: {1}<br />", key, Session[key].ToString());
                    }
                }
                catch
                { }
            }
            ViewBag.getSession = str;


            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;

            if (Session[SessionConstants.USER_ID] != null)
            {

                return View();
            }
            else
            {
                return RedirectToAction("Login", "Home");
            }
        }

        public ActionResult Feedback()
        {
            ViewBag.sessionIds = "Session Id: " + Session.SessionID.ToString() + ", " + SessionConstants.USER_ID + "=" + Session[SessionConstants.USER_ID] + ", " + SessionConstants.USER_NAME + "=" + Session[SessionConstants.USER_NAME] + ", " + SessionConstants.PASSWORD + "=" + Session[SessionConstants.PASSWORD] + ", " + SessionConstants.MODE + "=" + Session[SessionConstants.MODE] + ", " + SessionConstants.ACTIVITY_TYPE + "=" + Session[SessionConstants.ACTIVITY_TYPE] + ", " + SessionConstants.PROMO_CODE + "=" + Session[SessionConstants.PROMO_CODE] + ", " + SessionConstants.SPONSOR_DETAILS + "=" + Session[SessionConstants.SPONSOR_DETAILS];

            string str = null;
            foreach (string key in Session.Keys)
            {
                try
                {
                    if (Session[key] != null)
                    {

                        str += string.Format("{0}: {1}<br />", key, Session[key].ToString());
                    }
                }
                catch
                { }
            }
            ViewBag.getSession = str;


            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;

            if (Session[SessionConstants.USER_ID] != null)
            {

                return View();
            }
            else
            {
                return RedirectToAction("Login", "Home");
            }
        }

        public ActionResult OtherDeviceLogin()
        {
            ViewBag.sessionIds = "Session Id: " + Session.SessionID.ToString() + ", " + SessionConstants.USER_ID + "=" + Session[SessionConstants.USER_ID] + ", " + SessionConstants.USER_NAME + "=" + Session[SessionConstants.USER_NAME] + ", " + SessionConstants.PASSWORD + "=" + Session[SessionConstants.PASSWORD] + ", " + SessionConstants.MODE + "=" + Session[SessionConstants.MODE] + ", " + SessionConstants.ACTIVITY_TYPE + "=" + Session[SessionConstants.ACTIVITY_TYPE] + ", " + SessionConstants.PROMO_CODE + "=" + Session[SessionConstants.PROMO_CODE] + ", " + SessionConstants.SPONSOR_DETAILS + "=" + Session[SessionConstants.SPONSOR_DETAILS];

            string str = null;
            foreach (string key in Session.Keys)
            {
                try
                {
                    if (Session[key] != null)
                    {

                        str += string.Format("{0}: {1}<br />", key, Session[key].ToString());
                    }
                }
                catch
                { }
            }
            ViewBag.getSession = str;
            ViewBag.userName = Session[SessionConstants.USER_NAME];
            ViewBag.password = Session[SessionConstants.PASSWORD];

            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;
            if (Session[SessionConstants.USER_ID] != null)
            {

                return View();
            }
            else
            {
                return RedirectToAction("Login", "Home");
            }
        }

        public ActionResult OtherDeviceChangeLogin()
        {
            var model = new LoginPasswordModel();

            if (Session[SessionConstants.USER_ID] != null)
            {
                Int32 userId = Convert.ToInt32(Session[SessionConstants.USER_ID].ToString());
                DataRepository entities = new DataRepository();
                model = entities.getLogin_UserID(userId);
                return View(model);
            }
            else
            {
                return RedirectToAction("Login", "Home");
            }
        }

        [HttpPost]
        public JsonResult ChangeLoginDetail(LoginPasswordModel model)
        {
            Int32 userId = Convert.ToInt32(Session[SessionConstants.USER_ID].ToString());
            String result = "0";

            if (userId > 0 && model.user_name != null && model.password != null)
            {
                //Int32 userId = model.user_id;
                DataRepository entities = new DataRepository();
                var getResult = entities.callsp_update(userId, model.user_name, model.password);
                return Json(new { JsonResult = getResult }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(result, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult AboutApp()
        {
            //Session[SessionConstants.MODE] = ApplicationModeConstants.ANDROID_APP; //Only for Testing

            ViewBag.sessionIds = "Session Id: " + Session.SessionID.ToString() + ", " + SessionConstants.USER_ID + "=" + Session[SessionConstants.USER_ID] + ", " + SessionConstants.USER_NAME + "=" + Session[SessionConstants.USER_NAME] + ", " + SessionConstants.PASSWORD + "=" + Session[SessionConstants.PASSWORD] + ", " + SessionConstants.MODE + "=" + Session[SessionConstants.MODE] + ", " + SessionConstants.ACTIVITY_TYPE + "=" + Session[SessionConstants.ACTIVITY_TYPE] + ", " + SessionConstants.PROMO_CODE + "=" + Session[SessionConstants.PROMO_CODE] + ", " + SessionConstants.SPONSOR_DETAILS + "=" + Session[SessionConstants.SPONSOR_DETAILS];

            string str = null;
            foreach (string key in Session.Keys)
            {
                try
                {
                    if (Session[key] != null)
                    {

                        str += string.Format("{0}: {1}<br />", key, Session[key].ToString());
                    }
                }
                catch
                { }
            }
            ViewBag.getSession = str;


            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;

            if (Session[SessionConstants.USER_ID] != null)
            {
                return View();
            }
            else
            {
                return RedirectToAction("Login", "Home");
            }
        }

        public ActionResult ComplimentsOf()
        {
            ViewBag.sessionIds = "Session Id: " + Session.SessionID.ToString() + ", " + SessionConstants.USER_ID + "=" + Session[SessionConstants.USER_ID] + ", " + SessionConstants.USER_NAME + "=" + Session[SessionConstants.USER_NAME] + ", " + SessionConstants.PASSWORD + "=" + Session[SessionConstants.PASSWORD] + ", " + SessionConstants.MODE + "=" + Session[SessionConstants.MODE] + ", " + SessionConstants.ACTIVITY_TYPE + "=" + Session[SessionConstants.ACTIVITY_TYPE] + ", " + SessionConstants.PROMO_CODE + "=" + Session[SessionConstants.PROMO_CODE] + ", " + SessionConstants.SPONSOR_DETAILS + "=" + Session[SessionConstants.SPONSOR_DETAILS];

            string str = null;
            foreach (string key in Session.Keys)
            {
                try
                {
                    if (Session[key] != null)
                    {

                        str += string.Format("{0}: {1}<br />", key, Session[key].ToString());
                    }
                }
                catch
                { }
            }
            ViewBag.getSession = str;


            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;


            SponsorInputs345xDto model = new SponsorInputs345xDto();
            if (Session[SessionConstants.USER_ID] != null)
            {
                String getSponsor = String.Empty;
                if (Session[SessionConstants.PROMO_CODE] != null)
                {
                    getSponsor = Session[SessionConstants.PROMO_CODE].ToString();
                }

                SponsorAppService objSponsorAppService = new SponsorAppService();
                model = objSponsorAppService.GetSponsorInput345xData(getSponsor);
                return View(model);
            }
            else
            {
                return RedirectToAction("Login", "Home");
            }
        }

        #endregion


        public ActionResult UploadFiles()
        {
            //Response.Cache.SetCacheability(HttpCacheability.NoCache);
            if (Session[SessionConstants.USER_ID] != null)
            {
                Int32 userId = Convert.ToInt32(Session[SessionConstants.USER_ID].ToString());

                decimal Lx = 254;
                decimal Ly = 196;

                decimal newWidth = 254, newHeight = 197; //note: we set here newHeight=197 (value increment by one), to handle the error occur.
                var filename = string.Empty;

                foreach (string file in Request.Files)
                {
                    HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                    filename = hpf.FileName;
                    if (hpf.ContentLength == 0)
                        continue;
                    Image originalImg = System.Drawing.Image.FromStream(hpf.InputStream);
                    if (originalImg.Width > originalImg.Height)
                    {
                        decimal ratio = Convert.ToDecimal(originalImg.Width) / Convert.ToDecimal(originalImg.Height);
                        newWidth = ratio * newHeight;
                    }
                    else
                    {
                        decimal ratio = Convert.ToDecimal(originalImg.Height) / Convert.ToDecimal(originalImg.Width);
                        newHeight = ratio * newWidth;

                    }

                    //Rename the file according to UserId


                    //==== Get file extension.
                    string savedFileName = Path.Combine(Server.MapPath("~/TempUserWelcomeImage"), Path.GetFileName(hpf.FileName));
                    string extension = Path.GetExtension(hpf.FileName);
                    filename = Convert.ToInt32(Session[SessionConstants.USER_ID]) + extension;
                    savedFileName = Path.Combine(Server.MapPath("~/TempUserWelcomeImage"), filename);
                    //savedFileName = Path.Combine(Server.MapPath("~/TempUserWelcomeImage"), hpf.FileName);
                    hpf.SaveAs(savedFileName);


                    using (var image = Image.FromFile(savedFileName))
                    {
                        int x = 0;
                        int y = 0;
                        if (Convert.ToInt32(newWidth) > Lx)
                        {
                            x = Convert.ToInt32(newWidth) - Convert.ToInt32(Lx);
                            x = x / 2;
                        }
                        else
                        {
                            y = Convert.ToInt32(newHeight) - Convert.ToInt32(Ly);
                            y = y / 2;
                        }

                        Image resized = Imager.Resize(image, Convert.ToInt32(newWidth), Convert.ToInt32(newHeight), true);


                        var img = Imager.Crop(resized, new Rectangle(x, y, Convert.ToInt32(Lx), Convert.ToInt32(Ly)));

                        Imager.SaveJpeg(Path.Combine(Server.MapPath("~/UserWelcomeImage"), filename), img);
                    }



                    System.IO.File.Delete(savedFileName);
                } //,\"path\":\"" + r[0].ImagePath + "\"

                //We need to Update Image in the  Database:
                #region[Image Update in the database]

                UserAppService objUserAppService = new UserAppService();
                objUserAppService.UpdateWelcomeImage(userId, filename, DateTime.Now.ToString());



                #endregion

                return Content("{\"name\":\"" + filename + "\"}", "application/json");
            }
            else
            {
                return RedirectToAction("Login", "Home");
            }


        }



        [HttpPost]
        public JsonResult DeleteWelcomeImage()
        {
            String result = "0";
            Int32 userId = 0;

            if (Session[SessionConstants.USER_ID] != null)
            {
                userId = Convert.ToInt32(Session[SessionConstants.USER_ID].ToString());
            }

            if (userId > 0)
            {
                UserAppService objUserAppService = new UserAppService();
                objUserAppService.DeleteWelcomeImage(userId, DateTime.Now.ToString());
                result = "1";
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(result, JsonRequestBehavior.AllowGet);
            }
        }

    }
}
